<?php

namespace app\admin\controller\ykjp\purchase;

use app\common\controller\Backend;

/**
 * 入库审核
 *
 * @icon fa fa-circle-o
 */
class StoAudit extends Backend {

    protected $model = null;
    protected $searchFields = "name";
    protected $distinguish = true;
    protected $wherename = "storage.firmid";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\purchase\Storage;
        $this->view->assign("theWayList", $this->model->getTheWayList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index() {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                $row->getRelation('supplier')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审批
     */
    public function approval($ids = null) {
        if ($ids) {
            if ($this->request->isAjax()) {
                $type = $this->request->param("type");
                $stroModel = new \app\admin\model\ykjp\purchase\Stoproduct;
                if ($type == null) {
                    $this->error(__('Parameter %s can not be empty', 'type'));
                }
                $ids = $this->request->param("ids/a");
                $firmid = $this->auth->firmid;
                if ($type == "yes") {
                    $data = array("status" => "1", "reviewer_id" => $this->auth->id);
                    $productData = array("status" => "1");
                    $result = $this->model->where("id", "in", $ids)->update($data);
                    $str = $stroModel->where("storage_id", "in", $ids)->update($productData);
                    if ($result) {
                        $this->success(null, null, array("result" => "success"));
                    } else {
                        $this->error(__('operation failed'));
                    }
                } else {
                    $count = 0;
                    $reason = $this->request->param("reason");
                    if (!$reason) {
                        $this->error(__("Reason cannot be empty"));
                    }
                    $reason = strip_tags($reason);
                    $data = array("status" => "2", "reviewer_id" => $this->auth->id, "reason" => $reason);
                    $appData = $this->model->where("id", "in", $ids)->where("firmid", $firmid)->select();
                    if (!$appData) {
                        $this->error(__('operation failed'));
                    }
                    $stroModel = new \app\admin\model\ykjp\purchase\Stoproduct; //入库产品单
                    $purchaseModel = new \app\admin\model\ykjp\purchase\Order; //采购单
                    $purProModel = new \app\admin\model\ykjp\purchase\Product; //采购产品单
                    foreach ($appData as $key => $val) {
                        $id = $val['id'];
                        $allNums = 0;
                        $result = $this->model->where("id", $id)->where("firmid", $firmid)->update($data); //更新采购单的状态
                        if ($result) {
                            $count += $result;
                            $purchase_id = $val['purchase_id'];
                            if ($purchase_id != "" && $purchase_id > 0) {
                                $purData = $purchaseModel->where("id", $purchase_id)->find(); //获取采购单
                                $strData = $stroModel->where("storage_id", $val['id'])->select(); //获取入库产品
                                // var_dump($strData);exit;
                                if ($purData) {
                                    foreach ($strData as $pro) {
                                        $proId = $pro["purchase_proid"];
                                        $nums = $pro['nums'];
                                        $pruProd = $purProModel->where("id", $proId)->find(); //查找对应采购单产品
                                        if ($pruProd) {
                                            $wait_nums = $pruProd['wait_nums'] + $nums;
                                            $up = $purProModel->where("id", $proId)->update(array("wait_nums" => $wait_nums)); //修改采购单中的待出库数
                                            if ($up) {
                                                $allNums += $nums;
                                            }
                                        }
                                    }
                                    if ($allNums > 0) {
                                        $total_nums = $allNums + $purData['wait_nums'];
                                        $purchaseModel->where("id", $purData['id'])->update(array("wait_nums" => $total_nums));
                                    }
                                }
                                $dataProduct = array("status" => "2");
                                $udpteStr = $stroModel->where("storage_id", $id)->update($dataProduct);
                                if (!$udpteStr) {
                                    $this->model->where("id", $id)->where("firmid", $firmid)->update(array("status" => "0"));
                                }
                            }
                        }
                    }

                    if ($count) {
                        $this->success(null, null, array("result" => "success"));
                    } else {
                        $this->error(__('operation failed'));
                    }




                    //   $result=$this->model->where("id","in",$ids)->where("firmid",$firmid)->update($data);
                    //   if($result){
                    // 	 $this->success(null,null,array("result"=>"success"));
                    //   }else{
                    // 	 $this->error(__('operation failed'));
                    // }
                }
            }
        } else {
            $this->error(__('The request method is not in short supply'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 详情
     */
    public function detail($ids = null) {

        if ($ids) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->where("storage.id", $ids)
                    ->select();
            $stpModel = new \app\admin\model\ykjp\purchase\Stoproduct;
            $strProduct = $stpModel->with(['products'])->where("storage_id", $ids)->select();
            foreach ($strProduct as $key => $val) {
                $pro = json_decode($val['products']['prop']);
                $val['products']['prop'] = $this->model->object_array($pro);
            }
            $this->assign("detail", $list);
            $this->assign("product", $strProduct);
            return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'), "ykjp/purchase/sto_audit?ref=addtabs");
    }

}
